<?php
namespace App\Services;
use App\Models\MemberModel;

class MemberService{
    public function filterEmoji($str)
    {
        $str = preg_replace_callback( '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }

	/**
	 * 更新会员登录时间
	 * @param array $data
	 * @param string $telephone
	 * @return bool $res
	 */
	public function modifyMember($id,$data){
		$res = MemberModel::where('id',$id)->update($data);
		return $res;
	}

	/**
	 * 注册会员
	 * @param array $data
	 * @return bool $res
	 */
	public function insertMember($data){
		$res = MemberModel::insertGetId($data);
		return $res;
	}

	/**
	 * 获取会员详细信息
	 * @param string $telephone
	 * @return object $memberinfo
	 */
	public function getMemberInfo($telephone){
		$memberinfo = MemberModel::where('telephone',$telephone)->first();
		return $memberinfo;
	}

    public function getMemberInfoByid($id){
        $memberinfo = MemberModel::where('id',$id)->first();
        return $memberinfo;
    }

    public function getMemberInfoByOpenId($openid){
        $memberinfo = MemberModel::where('openid',$openid)->first();
        return $memberinfo;
    }

	/**
	 * 获取会员列表
	 * @param int $pagesize
	 * @param string $keywords
	 * @return objcet $memberlist
	 */
	public function getMemberList($pagesize,$keywords=''){
		$memberlist = MemberModel::orderBy('register_date','desc')
					 ->where('check','normal')
					 ->where(function($query) use ($keywords){
					 	if($keywords != ''){
					 		$pattern = "/^1[34578]\d{9}$/";
							preg_match($pattern, $keywords, $match);
							if(empty($match)){
								$query->where('member_name',$keywords);
							}else{
								$query->where('telephone',$keywords);
							}
					 	}
					 })
					 ->select('id','nick','telephone','thumb','isbuy','register_date')
					 ->paginate($pagesize);
            foreach($memberlist as $mtm=>$mst){
                if($mst->id > 116){
                    if($mst->nick == base64_encode(base64_decode($mst->nick))){
                        $memberlist[$mtm]->nick = $this->filterEmoji(base64_decode($mst->nick));
                    }
                }

            }

		return $memberlist;
	}

	/**
	 * 获取会员总条数
	 * @return $memberCount
	 */
	public function getMemberCount($start_date = '',$end_date = ''){
		$memberCount = MemberModel::where('check','normal')
					->where(function($query) use ($start_date){
						if($start_date != ''){
							$query->where('register_date','>=',$start_date);
						}
					})
					->where(function($query) use ($end_date){
						if($end_date != ''){
							$query->where('register_date','<=',$end_date);
						}
					})
					->select('id')
					->count();

		return $memberCount;
	}
}